package com.sskj.gocoin.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.util.SPUtil;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.component.DaggerUserDataComponent;
import com.sskj.gocoin.m.bean.Menu;
import com.sskj.gocoin.m.bean.UserInfo;
import com.sskj.gocoin.mine.data.GuideListBean;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.ImageUtil;
import com.sskj.gocoin.utils.LanguageUtil;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.utils.PhoneHideUtil;
import com.sskj.gocoin.utils.RxSchedulersHelper;
import com.sskj.gocoin.utils.SPUtils;
import com.sskj.gocoin.utils.TipUtil;
import com.sskj.gocoin.v.activity.AboutUsActivity;
import com.sskj.gocoin.v.activity.ApplyForShopActivity;
import com.sskj.gocoin.v.activity.CashAddressListActivity;
import com.sskj.gocoin.v.activity.ExchangeActivity;
import com.sskj.gocoin.v.activity.GoogleSettingActivity;
import com.sskj.gocoin.v.activity.InviteFriendActivity;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.PersonalActivity;
import com.sskj.gocoin.v.activity.SecurityCenterActivity;
import com.sskj.gocoin.v.activity.SellerApplyActivity;
import com.sskj.gocoin.v.base.BaseFragment;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author Hey
 * Create at  2019/03/29
 */
@Route(path = RConfig.MINE_FRAGMENT_MAIN)
public class MineFragment extends BaseFragment<MainActivity, MinePresenter> {

    @BindView(R2.id.img_head)
    ImageView imgHead;
    @BindView(R2.id.iv_vip)
    ImageView ivVip;
    @BindView(R2.id.notice_img)
    ImageView noticeImg;
    @BindView(R2.id.tv_account)
    TextView tvAccount;
    @BindView(R2.id.tv_uid)
    TextView tvUid;
    @BindView(R2.id.sign_img)
    ImageView signImg;
    @BindView(R2.id.tv_asset)
    TextView tvAsset;
    @BindView(R2.id.tv_asset_cny)
    TextView tvAssetCny;
    @BindView(R2.id.notice_switch)
    TextSwitcher noticeSwitch;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R2.id.menu)
    RecyclerView menuRecyclerView;
    BaseAdapter<Menu> menuAdapter;
    List<Menu> menuData = new ArrayList<>();
    private Disposable disposable;
    private AlertDialog shopDialog;

    private UserInfo mUserInfo;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine_n;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void initView() {
        LanguageUtil.changeAppLanguage(getActivity(), LanguageUtil.getAppLocale(App.INSTANCE), true);

        DaggerUserDataComponent.create().inject(this);
        ImageUtil.setCircleImage(R.mipmap.app_logo, imgHead);
        noticeImg.setImageResource(isEnglish ? R.mipmap.h_mine_notice_img_en : R.mipmap.h_mine_notice_img);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.requestUserInfo();
            } else {
                userData = null;
                updateStatus(null);
            }
        });
        noticeSwitch.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setTextColor(getResources().getColor(R.color.hint));
            return textView;
        });

        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {

            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                if (userData != null) {
                    mPresenter.requestUserInfo();
                }
            }
        });

        initMenu();
        ClickUtil.click(imgHead, () -> {
            if (mUserInfo == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);

                return;
            }
            startActivity(new Intent(getActivity(), PersonalActivity.class));
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            userViewModel.update();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void initData() {
        ClickUtil.click(signImg, () -> {
            mPresenter.signIn();
        });
        ClickUtil.click(tvAccount, () -> {
            if (mUserInfo == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);

                return;
            }
            startActivity(new Intent(getActivity(), PersonalActivity.class));
        });
        mPresenter.getNotice(1, 20);
    }

    private void initMenu() {
        menuData.add(new Menu(App.INSTANCE.getString(R.string.strMineFragment245), R.mipmap.h_mine_apply_seller, PersonalActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.strMineFragment204), R.mipmap.h_mine_security, SecurityCenterActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.strMineFragment205), R.mipmap.h_mine_asset_manager, AssetManagerActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.strMineFragment207), R.mipmap.h_mine_address, CashAddressListActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.exchange), R.mipmap.h_mine_exchange, ExchangeActivity.class));
        menuData.add(new Menu(getString(R.string.my_share), R.mipmap.h_mine_share, MyShareActivity.class));
        menuData.add(new Menu(getString(R.string.apply_market_seller), R.mipmap.h_mine_apply_market_seller, ApplyForShopActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.strMineFragment211), R.mipmap.h_mine_about, AboutUsActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.xmlactivity_google_setting20), R.mipmap.h_mine_setting, GoogleSettingActivity.class));  // 设置
        menuRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        menuAdapter = new BaseAdapter<Menu>(R.layout.item_main_menu, menuData, menuRecyclerView) {
            @Override
            public void bind(ViewHolder holder, Menu item) {
                holder.setText(R.id.menu_title, item.getText());
                holder.setImageResource(R.id.menu_icon, item.getIcon());
                if ((holder.getAdapterPosition() + 1) % 3 == 0 && holder.getAdapterPosition() != 0) {
                    holder.setVisible(R.id.menu_right_line, false);
                } else {
                    holder.setVisible(R.id.menu_right_line, true);
                }
                if (menuData.size() % 3 == 0) {
                    if (holder.getAdapterPosition() + 1 > 3 * (menuData.size() / 3 - 1)) {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    } else {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    }
                } else {
                    if ((holder.getAdapterPosition() + 1) > (menuData.size() - menuData.size() % 3)) {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    } else {
                        holder.setVisible(R.id.menu_bottom_line, true);
                    }
                }
                ClickUtil.click(holder.getView(R.id.menu_item), () -> {
                    /*if (holder.getAdapterPosition() == 5) {
                        if (mUserInfo == null)
                            return;
                        if (!mUserInfo.isIs_shop()) {
                            if (checkIdent(getContext())) {
                                Intent intent = new Intent(getContext(), item.getClz());
                                startActivity(intent);
                            }
                        } else {
                            //是否确认取消商家认证
                            shopDialog = TipUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.fabimineJavaMineFragment1), App.INSTANCE.getString(R.string.fabimineJavaMineFragment2), () -> {
                                mPresenter.requestRelieveBusiness(shopDialog);
                            });
                            shopDialog.show();
                        }
                    } else */if (holder.getAdapterPosition() == 6) {
                        Bundle bundle = new Bundle();
                        bundle.putString(Constans.INTENT_NOTICE_ID, "sqss");
                        ARouter.getInstance().build(RConfig.MINE_WEBVIEW).with(bundle).navigation();
                    } else {
                        Intent intent = new Intent(getContext(), item.getClz());
                        startActivity(intent);
                    }
                });
            }
        };
    }

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void signInSuccess() {
        if (isEnglish) {
            signImg.setImageResource(R.mipmap.h_mine_sign_p_en);
        } else {
            signImg.setImageResource(R.mipmap.h_mine_sign_p);
        }
    }

    public void setNotice(List<GuideListBean> list) {
        if (list != null && list.size() > 0) {
            if (disposable != null) {
                disposable.dispose();
            }
            Observable.interval(0, 5, TimeUnit.SECONDS)
                    .compose(RxSchedulersHelper.io_main())
                    .subscribe(new Observer<Long>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            disposable = d;
                        }

                        @Override
                        public void onNext(Long i) {
                            if (noticeSwitch != null) {
                                GuideListBean message = list.get((int) (i % list.size()));
                                String title = message.getTitle();
                                noticeSwitch.setText(title);
                                ClickUtil.click(noticeSwitch, () -> {
                                    ARouter.getInstance()
                                            .build(RConfig.APP_GUIDE_WEB)
                                            .withString(Constans.HEAD, App.INSTANCE.getString(R.string.mine_gonggao_detail))
                                            .withString(Constans.ID, message.getId())
                                            .withString(Constans.TIME, message.getCreate_time())
                                            .withString(Constans.TITLE, message.getTitle())
                                            .navigation();
                                });
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
    }

    DecimalFormat mFormat = new DecimalFormat("0.0000");

    public void updateStatus(UserInfo data) {
        mUserInfo = data;
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
        if (data != null) {
            SPUtils.putBean(getContext(), Constants.SP_USER_INFO, data);
            SPUtils.put(getContext(), Constants.SP_REALNAME, data.getRealname());
            SPUtils.put(MyAppLication.getApplication(), Constants.SP_REALNAME_STATUS, data.getStatus());
            SPUtils.put(MyAppLication.getApplication(), Constants.SP_REALNAME_STATUS_HIGH, data.getAuth_status());
            if (data.getQd() == 1) {
                signImg.setImageResource(isEnglish ? R.mipmap.h_mine_sign_p_en : R.mipmap.h_mine_sign_p);
            } else {
                signImg.setImageResource(isEnglish ? R.mipmap.h_mine_sign_en : R.mipmap.h_mine_sign);
            }
            String s = SPUtil.get(SPConfig.MOBILE, "");
            if (!s.contains("@")) {
                tvAccount.setText(data == null ? App.INSTANCE.getString(R.string.fabimineJavaMineFragment4) : PhoneHideUtil.getHide(s));
            } else {

                tvAccount.setText(data == null ? App.INSTANCE.getString(R.string.fabimineJavaMineFragment4) : PhoneHideUtil.getEmailHide(s));
            }
            tvUid.setText(data == null ? "UID:--" : "UID:" + data.getAccount());
            tvAsset.setText(data == null ? "--" : mFormat.format(data.getWallone()) + "");
            tvAssetCny.setText(data == null ? "--" : "≈" + NumberUtil.keep2(String.valueOf(data.getCny_money())) + " CNY");
            if (data.getWallone() < data.getMoney1()) {
                ivVip.setVisibility(View.INVISIBLE);
            } else {
                ivVip.setVisibility(View.VISIBLE);
            }
            if (data.getWallone() >= data.getMoney1()) {
                ivVip.setImageResource(R.mipmap.v1);
            }
            if (data.getWallone() >= data.getMoney2()) {
                ivVip.setImageResource(R.mipmap.v2);
            }
            if (data.getWallone() >= data.getMoney3()) {
                ivVip.setImageResource(R.mipmap.v3);
            }
            if (data.getWallone() >= data.getMoney4()) {
                ivVip.setImageResource(R.mipmap.v4);
            }
            if (data.getWallone() >= data.getMoney5()) {
                ivVip.setImageResource(R.mipmap.v5);
            }
//            if (mUserInfo.isIs_shop()) {
//                menuData.set(5, new Menu(App.INSTANCE.getString(R.string.fabimineJavaMineFragment12), R.mipmap.h_mine_apply_seller, SellerApplyActivity.class));
//                menuAdapter.notifyDataSetChanged();
//            } else {
//                menuData.set(5, new Menu(App.INSTANCE.getString(R.string.strMineFragment210), R.mipmap.h_mine_apply_seller, SellerApplyActivity.class));
//                menuAdapter.notifyDataSetChanged();
//            }
        }
    }

    public void onRelieveBusinessSuccess() {
        mUserInfo.is_shop = false;
        userData.setIs_shop(false);
        userViewModel.update(userData);
    }
}
